<?php

namespace app\index\controller;
use app\admin\library\Auth;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use app\common\controller\Api;
use app\common\library\Upload;
use think\Db;
use fpdf\Fpdf;
use fpdi\Fpdi;

class Pdf extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    public $config = [
        'app_id' => 'wx1f8725eef4e232a4',
        'secret' => '422171ef36ac1a93c055d0191cdfb751',
        'oauth' => [
            'scopes'   => ['snsapi_userinfo'],
            'callback' => '/index/Ques/oauth',
        ]
    ];
    public $url_img = ROOT_PATH.'public/pdf/';
    public $type_img = [
                        //考题开讲
                        1=>['name1'=>'1客户用.pdf','name2'=>'2全部.pdf','name3'=>'3打印用.pdf','autograph_wz'=>[123,224],'autograph_size'=>350],
                        //提分宝典
                        2=>['name1'=>'提分宝典客户用.pdf','name2'=>'提分宝典全部用.pdf','name3'=>'提分宝典空白.pdf','autograph_wz'=>[123,230],'autograph_size'=>350],
                    ];
    public $arr_local = [
        1=>[
          //身份证号
          'id_card'=>['size'=>8,'local'=>[[91,64],[95,64],[99,64],[103,64],[107,64],[111,64],[115,64],[118,64],[122,64],[126,64],[130,64],[134,64],[138,64],[142,64],[146,64],[150,64],[153,64],[157,64]]],
          //学生姓名
          'student_name'=>['size'=>8,'local'=>[40,64]],
          //版本 1=文科 2=理科 3=新高考
          //'edition'=>['name'=>'√','size'=>8,'local'=>[1=>[128,76],2=>[139,76],3=>[153,76]]],
          //版本 1=文科 2=理科 3=新高考
          'edition_text'=>['size'=>8,'local'=>[134,58.2]],
          //家长姓名
          'parent_name'=>['size'=>8,'local'=>[40,70]],
          //性别
          'gender_text'=>['size'=>8,'local'=>[68,64]],
           //手机号
          'phone'=>['size'=>8,'local'=>[68,70]],
          //固定电话
          'tel'=>['size'=>8,'local'=>[118,70]],
          //学生所在学校班级
          'grade'=>['size'=>8,'local'=>[55,76]],
          //所在地区联络地址
          'address'=>['size'=>8,'local'=>[55,81]],
          //最后一次成绩
          'last_exam'=>['size'=>8,'local'=>[55,87]],
          //email
          'email'=>['size'=>8,'local'=>[77,87]],
          //邮政编码
          'code'=>['size'=>8,'local'=>[127,87]],
          //截止日期 8月7号
          'closing_date'=>['size'=>8,'local'=>['y'=>[28,212],'m'=>[38,212],'d'=>[45,212]]],
          //签订日期
          'sign_date'=>['size'=>8,'local'=>['y'=>[103,233.5],'m'=>[112,233.5],'d'=>[120,233.5]]],
        ],
         2=>[
          //身份证号
          'id_card'=>['size'=>8,'local'=>[[92,58],[96,58],[100,58],[104,58],[108,58],[112,58],[116,58],[119,58],[123,58],[127,58],[131,58],[135,58],[139,58],[143,58],[147,58],[151,58],[154,58],[158,58]]],
          //学生姓名
          'student_name'=>['size'=>8,'local'=>[42,58]],
          //版本 1=文科 2=理科 3=新高考
          'edition'=>['name'=>'√','size'=>8,'local'=>[1=>[126,63],2=>[141,63],3=>[154,63]]],
          //科目
          'subject'=>['name'=>'√','size'=>8,'local'=>['物理'=>[48,68],'化学'=>[58,68],'生物'=>[67.5,68],'政治'=>[77,68],'历史'=>[86.5,68],'地理'=>[96,68],'技术'=>[106,68]]],
          //版本 1=文科 2=理科 3=新高考
          'edition_text'=>['size'=>8,'local'=>[134,58.2]],
          //家长姓名
          'parent_name'=>['size'=>8,'local'=>[41,72]],
          //性别
          'gender_text'=>['size'=>8,'local'=>[70,58]],
           //手机号
          'phone'=>['size'=>8,'local'=>[69,72]],
          //固定电话
          'tel'=>['size'=>8,'local'=>[137,72]],
          //学生所在学校班级
          'grade'=>['size'=>8,'local'=>[58,63]],
          //所在地区联络地址
          'address'=>['size'=>8,'local'=>[58,77]],
          //最后一次成绩
          'last_exam'=>['size'=>8,'local'=>[137,68]],
          //email
          'email'=>['size'=>8,'local'=>[77,87]],
          //邮政编码
          'code'=>['size'=>8,'local'=>[127,87]],
          //复读生高考日期
          'repeat_student'=>['size'=>8,'local'=>[111,147]],
          //合同号
          'contract_no'=>['size'=>14,'local'=>[30,18],'color'=>['233','56','47']],
          //截止日期 8月7号
          'closing_date'=>['size'=>8,'local'=>['y'=>[32.3,218.5],'m'=>[42,218.5],'d'=>[49,218.5]]],
          //签订日期
          'sign_date'=>['size'=>8,'local'=>['y'=>[100.5,238.995],'m'=>[110,238.995],'d'=>[118,238.995]]],
        ],
      ];

   /**
     * 公共
     * @author gzy
     * @date   2018年8月12日 09:15:00
     */
    public function _initialize(){
        parent::_initialize();
        $this->app = Factory::officialAccount($this->config);
        $this->auth = \app\admin\library\Auth::instance();
        $this->model = new \app\admin\model\shop\Contract;   
        $this->Fpdf = new Fpdf();
        $this->getProvinceOrderList = $this->model->getProvinceOrderList();
        $this->getGenderList = $this->model->getGenderList();
        $this->getProvinceOrderShortList = $this->model->getProvinceOrderShortList();
        $this->view->assign("editionList", $this->model->getEditionList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("genderList", $this->getGenderList);
        $this->ModelShop = Db::connect([
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '47.93.51.61',
            // 数据库名
            'database'    => 'shoptest2.fc62.com',
            // 数据库用户名
            'username'    => 'root',
            // 数据库密码
            'password'    => 'e7422254cd4628da',
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
        ]);
        $this->modelse = $this->ModelShop->table('eb_contract');
        $this->modelor = $this->ModelShop->table('eb_store_order');
        //$shopRow = $shop->table('ecs_order_info')->where(['order_id'=>$order])->find();

    }
    public function oauth()
    {
        $oauth = $this->app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();

        $_SESSION['wechat_user'] = $user->toArray();
        Session::set('wechat_user',$user->toArray());
        $targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];

        header('location:'. $targetUrl); // 跳转到 user/profile
        return $response = $this->app->oauth->scopes(['snsapi_userinfo'])
            ->redirect();
    }
   
    public function index(){
       $this->auth->logout();
       // 检测是否需要验证登录
       return redirect($this->request->domain().'/index/pdf/login');
        
    }  
    public function GetCartInfo($order_id,$key){

         $cartInfo = $this->ModelShop->table('eb_store_order_cart_info')->where('oid', $order_id)->column('cart_info', 'unique') ?: [];
            $info = [];
            foreach ($cartInfo as $k => $cart) {
                $cart = json_decode($cart, true);
                $cart['unique'] = $k;
           
                array_push($info, $cart);
                unset($cart);
            }
            $ai = 0;
            foreach ($info as $k => $v) {
                if(!isset($v['productInfo']['is_contract'])) continue;
                if($v['productInfo']['is_contract'] == 2){
                  if($this->ModelShop->table('eb_contract_type')->where('id',$v['productInfo']['contract_type'])->where('status',1)->count()){
                        for ($i=1; $i <= $v['cart_num']; $i++) {
                          if($ai+1 == $key){
                            $edition = explode(',', $v['productInfo']['attrInfo']['suk']);
                            if(!isset($edition[0]) || !isset($edition[2])) return false;
                            return ['subject'=>$v['spec_values'],'edition'=>$edition[0]??'','medium'=>$edition[2]??''];
                          }

                          $ai++;
                        }
                }
               }
            }
           return false;
    }
    public function generate_test($ids = null){
//      return '不可操作';
        $row =  $this->ModelShop->table('eb_contract')->where(['id'=>$ids])->find();
        if(!$row) $this->error('数据不存在');
         $info = $row;
         $info['province_text'] = $this->getProvinceOrderList[$info['province']];
          $info['city_text'] = $this->getProvinceOrderList[$info['city']];
          $info['area_text'] = $this->getProvinceOrderList[$info['area']];
          if($info['email']) unset($info['email']);
          if($info['code']) unset($info['code']);
           $info['repeat_student'] = "2020";
           /*$resu = $this->watermark($info,1);
           $params['contract_url'] = $resu['data'];  
           $resu = $this->watermark($info,2);
           $params['contract_all_url'] = $resu['data'];*/
           $resu = $this->watermark($info,3);
           $params['contract_blank_url'] = $resu['data'];
           $params['updatetime'] = time();
           $result = $this->ModelShop->table('eb_contract')->where('id', $ids)->update($params);
           if($result){
                $this->success('操作成功','',$ids);
            }else{
                $this->error('操作失败');
            }
    }
    /**
     * 生成
     */
    public function generate2($type = null,$userid = null,$order_id = null,$product_id = null,$key = null){
       if(!$type || !$userid || !$order_id || !$product_id || !$key)  $this->error('参数错误');
          $where = [
              'type'=>$type,
              'uid'=>$userid,
              'order_id'=>$order_id,
              'product_id'=>$product_id,
              'key'=>$key,
          ];

        if(!$order_info = $this->ModelShop->table('eb_store_order')->where('id',$order_id)->where('uid',$userid)->whereIn('status','0,1,2,3')->field('order_id,real_name,user_phone,user_school,user_address')->find()){
          $this->error('此订单不能签订合同','https://shoptest.fc62.com/order/list/');
        }
       
        if($row =  $this->ModelShop->table('eb_contract')->where($where)->find()){
          switch ($row['status']) {
             case 3:
             $this->error('此合同已经失效。','https://shoptest.fc62.com/');
              break;
             case 2:
             $this->error('您已经生成过合同请不要重复生成。','https://shoptest.fc62.com/order/sign/'.$order_info['order_id']);
              break;
          }
        }
        if(!$store_info = $this->GetCartInfo($order_id,$key)) $this->error('此订单不能签订合同','https://shoptest.fc62.com/order/list/');
        //print_r($this->modelse->getLastInsID());die;
       if ($this->request->isPost()){
            $params = $this->request->post();
            Db::startTrans();
            if($params){
              switch ($store_info['edition']) {
                case '全国版文科':
                   $params['edition'] = 1;
                  break;
               case '全国版理科':
                    $params['edition'] = 2;
                  break;
                default:
                 $params['edition'] = 3;
                  break;
              }
                $params['edition_txt'] = $store_info['edition'];
                $params['subject'] = $store_info['subject'];
                $params['order_sn'] = $order_info['order_id'];
                $params['medium'] = $store_info['medium'];
                $params['order_id'] = $order_id;
                $params['uid'] = $userid;
                $params['product_id'] = $product_id;
                $params['key'] = $key;
                $params['type'] = $type;
                $params['closing_date'] = strtotime(date('2021-08-07'));
                $params['sign_date'] = time();
                $params['updatetime'] = time();
                $info = $params;
               $info['province_text'] = $this->getProvinceOrderShortList[$info['province']];
               $info['city_text'] = $this->getProvinceOrderShortList[$info['city']];
               $info['area_text'] = $this->getProvinceOrderShortList[$info['area']];
                if(!$row){
                   if(!$params['contract_no'] = GenerateContractNo($info)) $this->error('生成合同号失败','https://shoptest.fc62.com/order/list/');
                   $params['createtime'] = time();
                   unset($params['user_address']);
                   $result = $this->ModelShop->table('eb_contract')->insert($params);
                   $ids = $this->ModelShop->table('eb_contract')->getLastInsID();
                 }else{
                   $info['contract_no'] = $row['contract_no']??'';
                   if(!GenerateContractNo($info,'464','edit')) $this->error('保存信息失败！');
                   $result = $this->ModelShop->table('eb_contract')->where('id', $row['id'])->update($params);
                   $ids = $row['id'];
                 }
                 if($result){
                      Db::commit();
                      $this->success('操作成功','',$ids);
                  }else{
                      Db::rollback();
                  }
            }
            Db::rollback();
            $this->error(__('Parameter %s can not be empty', ''));
       }
       
       if(!$row){ 
        $row['address_text'] = '';
          $row['parent_name'] = $order_info['real_name'];
          $row['phone'] = $order_info['user_phone'];
          $row['grade'] = $order_info['user_school'];
          $user_address = explode(' ', $order_info['user_address']);
           
          $row['address'] =$user_address[3]??'';
          $user_address[0] = preg_replace("/(市)/", "", $user_address[0]);
          $row['province'] = Db::name('area')->where('mergename','like','%'.$user_address[0].'%')->where('pid',0)->value('id');
          $row['city'] = Db::name('area')->where('mergename','like','%'.$user_address[1].'%')->where('pid', $row['province'])->value('id');
          $row['area'] = Db::name('area')->where('mergename','like','%'.$user_address[1].'%')->where('pid',$row['city'])->value('id');
          if(isset($user_address[3])) unset($user_address[3]);
          if($row['province'] && $row['city'] && $row['area'])
              $row['address_text'] = implode(' ',$user_address);
          
        }else{
          $row['address_text'] = '';
          $row['province_text'] = isset($row['province'])?$this->getProvinceOrderList[$row['province']]:'';
          $row['city_text'] = isset($row['city'])?$this->getProvinceOrderList[$row['city']]:'';
          $row['area_text'] = isset($row['area'])?$this->getProvinceOrderList[$row['area']]:'';
          if($row['province_text'] && $row['city_text'] && $row['area_text'])
          $row['address_text'] = $row['province_text'].' '.$row['city_text'].' '.$row['city_text'];
        }
       $this->view->assign("row", $row);
       $this->view->assign("urlpdf", '/pdf/'.$this->type_img[$type]['name1']);
       $this->view->assign("type", $type);
       $this->view->assign("userid", $userid);
       $this->view->assign("order_id", $order_id);
       $this->view->assign("product_id", $product_id);
       $this->view->assign("keyyy", $key);
      
 
       return $this->view->fetch();
  }  
   /**
     * 生成
     */
    public function handwriting2($ids=null){
       if(!$ids)  $this->error('参数错误');
       $row =  $this->ModelShop->table('eb_contract')->where(['id'=>$ids])->find();
       if(!$row) $this->error('数据不存在');
       if(!$order_info = $this->ModelShop->table('eb_store_order')->where('id',$row['order_id'])->where('uid',$row['uid'])->whereIn('status','0,1,2,3')->find()){
          $this->error('此订单不能签订合同','https://shoptest.fc62.com/order/list/');
        }
       if($row['status'] == 2) $this->error('不要重复提交','https://shoptest.fc62.com/order/sign/'.$order_info['order_id']);
       if(!$store_info = $this->GetCartInfo($row['order_id'],$row['key'])) $this->error('此订单不能签订合同','https://shoptest.fc62.com/order/list/');
       if ($this->request->isPost()){
            $params = $this->request->post();
            $delinfo = $info = $row;
            $info['province_text'] = $this->getProvinceOrderList[$info['province']];
            $info['city_text'] = $this->getProvinceOrderList[$info['city']];
            $info['area_text'] = $this->getProvinceOrderList[$info['area']];
            $info['gender_text'] = $this->getGenderList[$info['gender']];
            $info['sign_url'] = $params['sign_url'];
            Db::startTrans();
            if ($params) {
                  if($info['email']) unset($info['email']);
                   if($info['code']) unset($info['code']);
                   $info['repeat_student'] = "2020";
                   $resu = $this->watermark($info,1);
                   if($resu['true'] == 1){
                       $params['status'] = 2;
                       $params['contract_url'] = $resu['data'];
                       /*if(isset($info['contract_no'])) unset($info['contract_no']);*/
                       $resu = $this->watermark($info,2);
                       if($resu['true'] != 1){
                            Db::rollback();
                            $this->error('操作失败');
                       }
                       $params['contract_all_url'] = $resu['data'];
                       $resu = $this->watermark($info,3);
                       if($resu['true'] != 1){
                            Db::rollback();
                            $this->error('操作失败');
                       }
                       $params['contract_blank_url'] = $resu['data'];
                       $params['updatetime'] = time();
                       $result = $this->ModelShop->table('eb_contract')->where('id', $ids)->update($params);
                        if($result){
                            DeleteContractFile($delinfo);
                            Db::commit();
                            $this->success('操作成功','',$ids);
                        }else{
                            Db::rollback();
                            $this->error('操作失败');
                        }
                   }else{
                      Db::rollback();
                      $this->error('操作失败');
                   }
           
           }
            Db::rollback();
           $this->error('操作失败');
       }
        $this->view->assign("ids", $ids);
       return $this->view->fetch();
   }
     /**
     * 生成
     */
    public function question_success2($ids=null){
       if(!$ids)  $this->error('参数错误');
       $row =  $this->ModelShop->table('eb_contract')->where(['id'=>$ids])->find();
       if(!$row) $this->error('数据不存在');
       if($row['status'] == 1) $this->error('您还没有提交信息',  "/index/pdf/generate2/type/".$row['type']."/userid/".$row['uid']."/order_id/".$row['order_id']."/product_id/".$row['product_id']."/key/".$row['key']."");
       /*
        发短信隐藏。
       $info = $row->toArray();
       $info['tel'] = $info['phone'];
       write_log([],'',2,'contract_log');
       $result = send_message(34,[], [$info],'contract_log');*/
       $this->view->assign("row", $row);
       return $this->view->fetch();
   }
    /**
     * 生成
     */
    public function generate($ids = null,$userid = null){
       if(!$ids || !$userid)  $this->error('参数错误');
       $row = $this->model->where(['order_id'=>$ids,'userid'=>$userid])->find();
       if($row){
          if($row['status'] == 2){
             $this->error('您已经生成过合同请不要重复生成。','https://tmall.fc62.com/mobile/user.php?act=order_list');
          }
       } 
       if ($this->request->isPost()){
            $params = $this->request->post();
            Db::startTrans();
            if($params){
                $params['order_id'] = $ids;
                $params['userid'] = $userid;
                $params['closing_date'] = strtotime(date('Y-08-07'));
                $params['sign_date'] = time();
                if(!$row){
                   $result = $this->model->allowField(true)->save($params);
                   $ids = $this->model->getLastInsID();
                 }else{
                   $result = $row->allowField(true)->save($params);
                   $ids = $row->id;
                 }
                 if($result){
                      Db::commit();
                      $this->success('操作成功','',$ids);
                  }else{
                      Db::rollback();
                  }
            }
            Db::rollback();
            $this->error(__('Parameter %s can not be empty', ''));
       }
       $this->view->assign("row", $row);
       $this->view->assign("urlpdf", '/pdf/'.$this->type_img[1]['name1']);
       $this->view->assign("ids", $ids);
       $this->view->assign("userid", $userid);
       return $this->view->fetch();
  }  
    /**
     * 生成
     */
    public function handwriting($ids=null){
       if(!$ids)  $this->error('参数错误');
       $row = $this->model->where(['id'=>$ids])->find();
       if(!$row) $this->error('数据不存在');
       if($row['status'] == 2) $this->error('不要重复提交','https://tmall.fc62.com/mobile/user.php?act=order_list');
       if ($this->request->isPost()){
            $params = $this->request->post();
            $delinfo = $info = $row->toArray();
            $info['sign_url'] = $params['sign_url'];
            Db::startTrans();
            if ($params) {
                   $resu = $this->watermark($info,1);
                   if($resu['true'] == 1){
                       $params['status'] = 2;
                       $params['contract_url'] = $resu['data'];
                       if(isset($info['contract_no'])) unset($info['contract_no']);
                       $resu = $this->watermark($info,2);
                       if($resu['true'] != 1){
                            Db::rollback();
                            $this->error('操作失败');
                       }
                       $params['contract_all_url'] = $resu['data'];
                       $resu = $this->watermark($info,3);
                       if($resu['true'] != 1){
                            Db::rollback();
                            $this->error('操作失败');
                       }
                       $params['contract_blank_url'] = $resu['data'];
                       $result = $row->save($params);
                        if($result){
                            DeleteContractFile($delinfo);
                            Db::commit();
                            $this->success('操作成功','',$ids);
                        }else{
                            Db::rollback();
                            $this->error('操作失败');
                        }
                   }else{
                      Db::rollback();
                      $this->error('操作失败');
                   }
           
           }
            Db::rollback();
           $this->error('操作失败');
       }
        $this->view->assign("ids", $ids);
       return $this->view->fetch();
   }
    /**
     * 生成
     */
    public function question_success($ids=null){
       if(!$ids)  $this->error('参数错误');
       $row = $this->model->where(['id'=>$ids])->find();
       if(!$row) $this->error('数据不存在');
       if($row['status'] == 1) $this->error('您还没有提交信息','/index/pdf/generate/ids/'.$row['order_id'].'/userid/'.$row['userid'].'');
       /*
        发短信隐藏。
       $info = $row->toArray();
       $info['tel'] = $info['phone'];
       write_log([],'',2,'contract_log');
       $result = send_message(34,[], [$info],'contract_log');*/
       $this->view->assign("row", $row);
       return $this->view->fetch();
   }
  /**
     * 生成苏回音
     */
    public function watermark($arr = [],$type = 1){
        $this->Fpdi = new Fpdi();
        if(!isset($this->type_img[$arr['type']]['name'.$type])) return ['true'=>1,'msg'=>'操作成功','data'=>''];
            // 设置字体
        $this->Fpdi->AddGBFont('Arial', '宋体');

        // get the page count
        $pageCount = $this->Fpdi->setSourceFile($this->url_img.$this->type_img[$arr['type']]['name'.$type]);
        $arr['address'] = $arr['province_text'].$arr['city_text'].$arr['area_text'].$arr['address'];
              //设置路径目录信息
        $url = ROOT_PATH . 'public/uploads/pdf/'.date("Ymd").'/'.date('YmdHis') . uniqid().'.pdf';  
        $dir_name = dirname($url);
         //目录不存在就创建
        if(!file_exists($dir_name)) {
            //iconv防止中文名乱码
           $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $imglName = "uploads/pdf/".date("Ymd")."/".date('YmdHis') . uniqid().'.pdf';
        $no_url  = ''.request()->domain().'/'.$imglName.'';
        // iterate through all pages
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++)
        {

          // import a page
          $templateId =  $this->Fpdi->importPage($pageNo);

          // get the size of the imported page
          $size =  $this->Fpdi->getTemplateSize($templateId);

          // create a page (landscape or portrait depending on the imported page size)
          if ($size['w'] > $size['h'])  $this->Fpdi->AddPage('L', array($size['w'], $size['h']));
          else  $this->Fpdi->AddPage('P', array($size['w'], $size['h']));
          // use the imported page
           $this->Fpdi->useTemplate($templateId);
          // 只设置第一个pdf页面
          foreach ($arr as $key => $value) {
              switch ($key) {
                case 'edition':
                    if(isset($this->arr_local[$arr['type']][$key]['color'])){
                            $this->Fpdi->SetTextColor($this->arr_local[$arr['type']][$key]['color'][0],$this->arr_local[$arr['type']][$key]['color'][1],$this->arr_local[$arr['type']][$key]['color'][2]);
                    }else{
                               $this->Fpdi->SetTextColor(0,0,0);
                    }
                    // 设置字体
                     $this->Fpdi->SetFont('Arial', '', $this->arr_local[$arr['type']][$key]['size']);
                    // 设置位置
                     $this->Fpdi->SetXY($this->arr_local[$arr['type']][$key]['local'][$value][0],$this->arr_local[$arr['type']][$key]['local'][$value][1]);
                    // 写入内容
                     $this->Fpdi->Write (7, iconv("utf-8","gbk",$this->arr_local[$arr['type']][$key]['name']));
                  break; 
                case 'subject':
                   if(!$value) continue;
                   if(isset($this->arr_local[$arr['type']][$key]['color'])){
                            $this->Fpdi->SetTextColor($this->arr_local[$arr['type']][$key]['color'][0],$this->arr_local[$arr['type']][$key]['color'][1],$this->arr_local[$arr['type']][$key]['color'][2]);
                   }else{
                               $this->Fpdi->SetTextColor(0,0,0);
                   }
                   $subject = explode(',', $value);
                     if($subject){
                      foreach ($subject as $k => $v) {
                        if(isset($this->arr_local[$arr['type']][$key]['local'][$v])){
                        // 设置字体
                          $this->Fpdi->SetFont('Arial', '', $this->arr_local[$arr['type']][$key]['size']);
                          // 设置位置
                            $this->Fpdi->SetXY($this->arr_local[$arr['type']][$key]['local'][$v][0],$this->arr_local[$arr['type']][$key]['local'][$v][1]);   
                            $this->Fpdi->Write (7, iconv("utf-8","gbk",$this->arr_local[$arr['type']][$key]['name']));
                         }
                       }
                     }
                  break; 
               case 'id_card':
                  if(isset($this->arr_local[$arr['type']][$key]['color'])){
                            $this->Fpdi->SetTextColor($this->arr_local[$arr['type']][$key]['color'][0],$this->arr_local[$arr['type']][$key]['color'][1],$this->arr_local[$arr['type']][$key]['color'][2]);
                   }else{
                               $this->Fpdi->SetTextColor(0,0,0);
                   }
                   $ex = preg_split("//", $value, -1, PREG_SPLIT_NO_EMPTY);
                   // 设置字体
                     $this->Fpdi->SetFont('Arial', '', $this->arr_local[$arr['type']][$key]['size']);
                  
                   foreach ($ex as $k => $v) {
                    // 设置位置
                     $this->Fpdi->SetXY($this->arr_local[$arr['type']][$key]['local'][$k][0],$this->arr_local[$arr['type']][$key]['local'][$k][1]);
                    // 写入内容
                     $this->Fpdi->Write (7, iconv("utf-8","gbk",$v));
                   }
                  # code...
                  break;  
              case 'closing_date':
              case 'sign_date':
                     if(isset($this->arr_local[$arr['type']][$key]['color'])){
                            $this->Fpdi->SetTextColor($this->arr_local[$arr['type']][$key]['color'][0],$this->arr_local[$arr['type']][$key]['color'][1],$this->arr_local[$arr['type']][$key]['color'][2]);
                          }else{
                               $this->Fpdi->SetTextColor(0,0,0);
                          }
                 // 设置字体
                     $this->Fpdi->SetFont('Arial', '', $this->arr_local[$arr['type']][$key]['size']);
                    //年
                     $this->Fpdi->SetXY($this->arr_local[$arr['type']][$key]['local']['y'][0],$this->arr_local[$arr['type']][$key]['local']['y'][1]);
                     $this->Fpdi->Write (7, iconv("utf-8","gbk",date('Y',$value)));
                      //月
                     $this->Fpdi->SetXY($this->arr_local[$arr['type']][$key]['local']['m'][0],$this->arr_local[$arr['type']][$key]['local']['m'][1]);
                     $this->Fpdi->Write (7, iconv("utf-8","gbk",date('m',$value)));
                      //日
                     $this->Fpdi->SetXY($this->arr_local[$arr['type']][$key]['local']['d'][0],$this->arr_local[$arr['type']][$key]['local']['d'][1]);
                     $this->Fpdi->Write (7, iconv("utf-8","gbk",date('d',$value)));
                  # code...
                  break;
              case 'student_name':
              case 'parent_name':
              case 'phone':
              case 'tel':
              case 'grade':
              case 'last_exam':
              case 'address':
              case 'email':
              case 'gender_text':
              case 'edition_text':
              case 'code':
              case 'contract_no':
              case 'repeat_student':
                        if(isset($this->arr_local[$arr['type']][$key]['color'])){
                            $this->Fpdi->SetTextColor($this->arr_local[$arr['type']][$key]['color'][0],$this->arr_local[$arr['type']][$key]['color'][1],$this->arr_local[$arr['type']][$key]['color'][2]);
                          }else{
                               $this->Fpdi->SetTextColor(0,0,0);
                          }
                      // 设置字体
                     $this->Fpdi->SetFont('Arial', '', $this->arr_local[$arr['type']][$key]['size']);
                    // 设置位置
                     $this->Fpdi->SetXY($this->arr_local[$arr['type']][$key]['local'][0],$this->arr_local[$arr['type']][$key]['local'][1]);
                    // 写入内容
                     $this->Fpdi->Write (7, iconv("utf-8","gbk",$value));
                  # code...
                  break;
              case 'sign_url':
                                // Image参数：文件，x坐标，y坐标，宽，高
                $this->Fpdi->Image(ROOT_PATH.'public/'.$value,$this->type_img[$arr['type']]['autograph_wz'][0],$this->type_img[$arr['type']]['autograph_wz'][1],10,10);
                  # code...
                  break;
                default:
              
                  break;
              }
           
          }
   
              //插入图片
              // Image参数：文件，x坐标，y坐标，宽，高
              // $pdf->Image('timg.jpeg',50,15,44,40);
         

      }
       $this->Fpdi->Output($imglName);
       return ['true'=>1,'msg'=>'操作成功','data'=>$no_url];
 
    }
    
    public function upload(){
        //是否有图片上传
        if ($this->request->isPost()){
            $params = $this->request->post();
            $upload = new Upload();
            $upload->path(ROOT_PATH.'public/pdf/upload');//上传 发货凭证
            $file = $upload->upbase($params['file'],'/pdf/upload/');
            if($file){
                 $this->success('操作成功','',$file);
            }else{
                 $this->error($upload->error());
            }
        }
    }
    /**
     * 测试
     */
    public function test() {

     $type = 2;
     //print_r($this->arr_local[$type]['contract_no']['color']);die;
     $arr = [
        //身份证号
        'id_card'=>'41080319960219005X',
        //学生姓名
        'student_name'=>'郜振宇',
        //版本 1=文科 2=理科 3=新高考
        'edition'=>'3',
        //性别 1=男 2=女
        'gender_text'=>'男',
        //家长姓名
        'parent_name'=>'郜振宇家长',
         //手机号
        'phone'=>'13261557827',
        //固定电话
        'tel'=>'01092234',
        //学生所在学校班级
        'grade'=>'北京大学',
        //所在地区联络地址
        'address'=>'北京市昌平区',
        //最后一次成绩
        'last_exam'=>'100',
        //科目
        'subject'=>'物理,地理,技术,化学,生物,政治,历史',
        //截止日期 8月7号
        'closing_date'=>'1596729600',
        //签订日期
        'sign_date'=>time(),
        //合同号
        'contract_no'=>'1234567890192',
         //复读生高考日期
        'repeat_student'=>'2020',
      
        //'s'=>'1234567890192',
      ];
       $this->Fpdi = new Fpdi();
         // 设置字体
     $this->Fpdi->AddGBFont('Arial', '宋体');

       // get the page count
      $pageCount = $this->Fpdi->setSourceFile($this->url_img.$this->type_img[$type]['name1']);

      // iterate through all pages
      for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++)
      {

          // import a page
          $templateId =  $this->Fpdi->importPage($pageNo);

          // get the size of the imported page
          $size =  $this->Fpdi->getTemplateSize($templateId);

          // create a page (landscape or portrait depending on the imported page size)
          if ($size['w'] > $size['h'])  $this->Fpdi->AddPage('L', array($size['w'], $size['h']));
          else  $this->Fpdi->AddPage('P', array($size['w'], $size['h']));

          // use the imported page
           $this->Fpdi->useTemplate($templateId);
        
              foreach ($arr as $key => $value) {
                  switch ($key) {
                    case 'edition':
                        // 设置字体
                         $this->Fpdi->SetFont('Arial', '', $this->arr_local[$type][$key]['size']);
                        // 设置位置
                         $this->Fpdi->SetXY($this->arr_local[$type][$key]['local'][$value][0],$this->arr_local[$type][$key]['local'][$value][1]);
                        // 写入内容
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",$this->arr_local[$type][$key]['name']));
                      break; 
                   case 'subject':
                   $subject = explode(',', $value);
                     if($subject){
                      foreach ($subject as $k => $v) {
                        // 设置字体
                       $this->Fpdi->SetFont('Arial', '', $this->arr_local[$type][$key]['size']);
                      // 设置位置
                       $this->Fpdi->SetXY($this->arr_local[$type][$key]['local'][$v][0],$this->arr_local[$type][$key]['local'][$v][1]);   
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",$this->arr_local[$type][$key]['name']));
                       }
                     }
                  break; 
                   case 'id_card':
                       $ex = preg_split("//", $value, -1, PREG_SPLIT_NO_EMPTY);
                       // 设置字体
                         $this->Fpdi->SetFont('Arial', '', $this->arr_local[$type][$key]['size']);
                      
                       foreach ($ex as $k => $v) {
                        // 设置位置
                         $this->Fpdi->SetXY($this->arr_local[$type][$key]['local'][$k][0],$this->arr_local[$type][$key]['local'][$k][1]);
                        // 写入内容
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",$v));
                       }
                     
                        
                      # code...
                      break;  
                  case 'closing_date':
                  case 'sign_date':
                     // 设置字体
                         $this->Fpdi->SetFont('Arial', '', $this->arr_local[$type][$key]['size']);
                        //年
                         $this->Fpdi->SetXY($this->arr_local[$type][$key]['local']['y'][0],$this->arr_local[$type][$key]['local']['y'][1]);
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",date('Y',$value)));
                          //月
                         $this->Fpdi->SetXY($this->arr_local[$type][$key]['local']['m'][0],$this->arr_local[$type][$key]['local']['m'][1]);
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",date('m',$value)));
                          //日
                         $this->Fpdi->SetXY($this->arr_local[$type][$key]['local']['d'][0],$this->arr_local[$type][$key]['local']['d'][1]);
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",date('d',$value)));
                      # code...
                      break;
                    
                    default:
                           // 设置字体
                         $this->Fpdi->SetFont('Arial', '', $this->arr_local[$type][$key]['size']);
                         if(isset($this->arr_local[$type][$key]['color'])){
                            $this->Fpdi->SetTextColor($this->arr_local[$type][$key]['color'][0],$this->arr_local[$type][$key]['color'][1],$this->arr_local[$type][$key]['color'][2]);
                          }else{
                               $this->Fpdi->SetTextColor(0,0,0);
                          }
                        // 设置位置
                         $this->Fpdi->SetXY($this->arr_local[$type][$key]['local'][0],$this->arr_local[$type][$key]['local'][1]);
                        // 写入内容
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",$value));
                  
                      break;
                  }
               
              }
              // Image参数：文件，x坐标，y坐标，宽，高
              $this->Fpdi->Image(ROOT_PATH.'public/pdf/upload/202003231531385e7865da83896.png',$this->type_img[$type]['autograph_wz'][0],$this->type_img[$type]['autograph_wz'][1],10,10);
              //插入图片
              // Image参数：文件，x坐标，y坐标，宽，高
              // $pdf->Image('timg.jpeg',50,15,44,40);

      }
       $this->Fpdi->Output($this->url_img.'2020word.pdf');
    }
    /**
     * 函数说明：验证身份证是否真实
     * 注：加权因子和校验码串为互联网统计  尾数自己测试11次 任意身份证都可以通过
     * 传递参数：
     * $number身份证号码
     * 返回参数：
     * true验证通过
     * false验证失败
     */
    function isIdCard($number) {
        $sigma = '';
        //加权因子 
        $wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        //校验码串 
        $ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        //按顺序循环处理前17位 
        for ($i = 0;$i < 17;$i++) { 
            //提取前17位的其中一位，并将变量类型转为实数 
            $b = (int) $number{$i}; 
            //提取相应的加权因子 
            $w = $wi[$i]; 
            //把从身份证号码中提取的一位数字和加权因子相乘，并累加 得到身份证前17位的乘机的和 
            $sigma += $b * $w;
        }
    //echo $sigma;die;
        //计算序号  用得到的乘机模11 取余数
        $snumber = $sigma % 11; 
        //按照序号从校验码串中提取相应的余数来验证最后一位。 
        $check_number = $ai[$snumber];
        if ($number{17} == $check_number) {
            return true;
        } else {
            return false;
        }
    }

    
   
  

}
